<?php
use Phalcon\Paginator\Adapter\Model as PaginatorModel;

class TaskController extends ControllerBase{
    public function initialize(){
        header("Content-type:text/html;charset=utf-8");
    }
    //任务大厅首页
    public function indexAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //淘宝任务大厅
    public function tbtaskAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            $where='';
            //若点击搜索按钮，则移除所有session，并根据用户输入进行搜索
            if($this->request->isPost()){
                $this->session->remove('buyerLevel');
                $this->session->remove('taskEntrance');
                $this->session->remove('payType');
                $this->session->remove('taskPrice');
                $data=$this->request->getPost();
                if(!empty($data['searchKey'])&&!empty($data['searchWord'])){
                    if($data['searchKey']=='task_no'){
                        $where=" and t.task_serial='".$data['searchWord']."'";
                    }elseif($data['searchKey']=='nickname'){
                        $where=" and u.user_name='".$data['searchWord']."'";
                    }
                }
            }
            $levelArr=array(0,0,0,0,0,0,0);
            //任务星级筛选
            if($this->session->has('buyerLevel')){
                $buyerLevel=$this->session->get('buyerLevel');
                if(count($buyerLevel)<7){
                    $where.=" and t.task_buyer_level in (";
                    foreach($buyerLevel as $v){
                        $where.=$v.",";
                    }
                    $where=rtrim($where,",").")";
                }
                foreach($buyerLevel as $v){
                    $levelArr[$v-1]=$v;
                }
            }
            //任务入口筛选
            if($this->session->has('taskEntrance')){
                $taskEntrance=$this->session->get('taskEntrance');
                if(count($taskEntrance)==1){
                    $where.=" and t.task_entrance=".$taskEntrance[0];
                }
                $this->view->setVar('taskEntrance',$taskEntrance);
            }
            //任务支付类型筛选
            if($this->session->has('payType')){
                $payType=$this->session->get('payType');
                if(count($payType)==1){
                    $where.=" and t.task_pay_type=".$payType[0];
                }
                $this->view->setVar('payType',$payType);
            }
            //任务价格筛选
            if($this->session->has('taskPrice')){
                $taskPrice=$this->session->get('taskPrice');
                $priceArr=explode(';',$taskPrice);
                $where.=" and task_total_price>".$priceArr[0]." and task_total_price<=".$priceArr[1];
                $this->view->setVar('taskPrice',$taskPrice);
            }
            $pageOffset=5;//页码偏移量
            $limit=3;//每页显示记录数
            $currentPage=(int)@$_GET["page"]<1?1:@$_GET["page"];
            //$phql="select t.*,u.* from Task t left join User u on t.task_user_id=u.user_id where t.task_type=1 and t.task_buyer_level in (1,2,3,4) and t.task_pay_type=2 order by t.task_release_time desc";
            $phql="select t.*,u.* from Task t left join User u on t.task_user_id=u.user_id where t.task_type=1 and t.task_num>0 and t.task_is_release=1".$where." order by t.task_release_time desc";
            $taskList=$this->modelsManager->executeQuery($phql);
            $paginator=new PaginatorModel(
                array(
                    "data"  => $taskList,
                    "limit" => $limit,
                    "page"  => $currentPage
                )
            );
            $page=$paginator->getPaginate();
            if($page->last<=$pageOffset*2+1){  //若要总页数小于或等于要显示的页码数，让起始页码等于1，结束页码等于总页数
                $startnum=1;
                $lastnum=$page->last;
            }else{  //若总页数大于要显示的页码数
                if($currentPage-$pageOffset<=1){   //若当前页码减去偏移量小于或等于1，让起始页码等于1，结束页码等于要显示的页码数
                    $startnum=1;
                    $lastnum=$pageOffset*2+1;
                }else{  //若当面页码减去偏移量大于1
                    $startnum=$currentPage-$pageOffset <= 1 ? 1 : $currentPage-$pageOffset;   //若当前页码减去偏移量小于或等于1，则让起始页码等于1，否则就让起始页码等于当前页码减去偏移量
                    $startnum=$currentPage+$pageOffset >= $page->last ? $page->last-$pageOffset*2 : $currentPage-$pageOffset; //若当前页码加上偏移量大于或等于总页数，则让起始页码等于总页数减去偏移量的2倍，否则就让起始页码等于当前页码减去偏移量
                    $lastnum=$currentPage+$pageOffset >= $page->last ? $page->last:$currentPage+$pageOffset;  //若当前页码加上偏移量大于或等于总页数，则让结束页码等于总页数，否则就让结束页码等于当前页码加上偏移量
                }
            }
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'page'=>$page,
                'startNum'=>$startnum,
                'lastNum'=>$lastnum,
                'currentPage'=>$currentPage,
                'levelArr'=>$levelArr
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //京东任务大厅
    public function jdtaskAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //任务模板显示页
    public function tasktemplateAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            //订单表弄好后，这里需要修改
            $taskList=Task::find(array("task_is_save=2 and task_is_release=2"));
            if($taskList->count()>0){
                $str='';
                foreach($taskList as $v){
                    $str.=$v->task_id.',';
                }
                $str=rtrim($str,',');
                $phql = "delete from Task where task_id in (" . $str . ")";
                $this->modelsManager->executeQuery($phql);
            }
            $phql="select t.*,s.* from Task t left join Shop s on t.task_shop_id=s.shop_id where t.task_is_save=1 order by task_release_time desc";
            $taskTemplate=$this->modelsManager->executeQuery($phql);
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'taskTemplate'=>$taskTemplate
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //新建淘宝任务
    public function tbnewtaskAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            $userId=$this->session->get('userId');
            //淘宝店铺
            $condition="shop_user_id=?1 and shop_status=1 and shop_type=1";
            $param=array(1=>$userId);
            $shopList=Shop::find(array(
                $condition,
                "bind"=>$param
            ));
            //商品标签
            $condition="tag_type=1";
            $tagList=Tag::find(array($condition));
            //地区
            $condition="Pid=0 and Id not in (990000,0)";
            $areaList=China::find(array($condition));
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'shopList'=>$shopList,
                'tagList'=>$tagList,
                'areaList'=>$areaList
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //编辑淘宝任务
    public function tbedittaskAction($id){
        $isLogin=$this->isLogin();
        if($isLogin){
            $userId=$this->session->get('userId');
            $task=Task::findFirst($id);
            if(!$task){
                $this->response->redirect("/task/tasktemplate");
            }
            //淘宝店铺
            $condition="shop_user_id=?1 and shop_status=1 and shop_type=1";
            $param=array(1=>$userId);
            $shopList=Shop::find(array(
                $condition,
                "bind"=>$param
            ));
            //商品标签
            $condition="tag_type=1";
            $tagList=Tag::find(array($condition));
            //地区
            $condition="Pid=0 and Id not in (990000,0)";
            $areaList=China::find(array($condition));
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'shopList'=>$shopList,
                'tagList'=>$tagList,
                'areaList'=>$areaList,
                'task'=>$task
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //新建京东任务
    public function jdnewtaskAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            $userId=$this->session->get('userId');
            //京东店铺
            $condition="shop_user_id=?1 and shop_status=1 and shop_type=2";
            $param=array(1=>$userId);
            $shopList=Shop::find(array(
                $condition,
                "bind"=>$param
            ));
            //地区
            $condition="Pid=0 and Id not in (990000,0)";
            $areaList=China::find(array($condition));
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'shopList'=>$shopList,
                'areaList'=>$areaList
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //绑定淘宝店铺
    public function bindtbAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            if($this->request->isPost()){
                $data=$this->request->getPost();
                if(!empty(trim($data['storeLink']))){
                    $shopInfo=array();
                    $shopInfo['shop_user_id']=$this->session->get('userId');
                    $shopInfo['shop_time']=time();
                    $shopInfo['shop_type']=1;
                    $contents=file_get_contents($data['storeLink']);
                    $contents=iconv("GBK", "utf-8",$contents);
                    if(preg_match("/tmall.com/is",$data['storeLink'])){
                        //天猫店只获取店铺名
                        if(preg_match("/<li.*?class=\"shopkeeper\".*?<a.*?>(.*?)<\/a>/is",$contents,$matches)){
                            $shopInfo['shop_name']=$matches[1];
                            $shopInfo['shop_keeper']=$matches[1];
                            $shop=new Shop();
                            if($shop->save($shopInfo)){
                                echo "<script>alert('店铺绑定成功！');location.href='/task/shoplist';</script>";exit;
                            }else{
                                echo "<script>alert('店铺绑定失败，请稍候重试或联系客服进行绑定！');location.href='/task/bindtb';</script>";exit;
                            }
                        }else{
                            echo "<script>alert('店铺绑定失败，请检查您的商品链接是否正确或联系客服进行绑定！');location.href='/task/bindtb';</script>";exit;
                        }
                    }else{
                        if(preg_match("/g_config.pinusEnterprise = true;/s",$contents)){
                            //淘宝企业店获取店铺名与掌柜名
                            if(!preg_match("/shopName.*?\:.*?\'(.*?)\'/s",$contents,$matches1)||!preg_match("/sellerNick.*?\:.*?\'(.*?)\'/s",$contents,$matches2)){
                                echo "<script>alert('店铺绑定失败，请检查您的商品链接是否正确或联系客服进行绑定！');location.href='/task/bindtb';</script>";exit;
                            }else{
                                $jsonStr='{"storeName":"'.$matches1[1].'"}';
                                $jsonArr=json_decode($jsonStr,true);
                                $shopInfo['shop_name']=$jsonArr['storeName'];
                                $shopInfo['shop_keeper']=$matches2[1];
                                $shop=new Shop();
                                if($shop->save($shopInfo)){
                                    echo "<script>alert('店铺绑定成功！');location.href='/task/shoplist';</script>";exit;
                                }else{
                                    echo "<script>alert('店铺绑定失败，请稍候重试或联系客服进行绑定！');location.href='/task/bindtb';</script>";exit;
                                }
                            }
                        }else{
                            //淘宝个人店获取店铺名与掌柜名
                            if(preg_match("/class=\"tb-seller-bail\"/s",$contents,$matches)){
                                if(!preg_match("/shopName.*?\:.*?\'(.*?)\'/s",$contents,$matches1)||!preg_match("/sellerNick.*?\:.*?\'(.*?)\'/s",$contents,$matches2)){
                                    echo "<script>alert('店铺绑定失败，请检查您的商品链接是否正确或联系客服进行绑定！');location.href='/task/bindtb';</script>";exit;
                                }else{
                                    $jsonStr='{"storeName":"'.$matches1[1].'"}';
                                    $jsonArr=json_decode($jsonStr,true);
                                    $shopInfo['shop_name']=$jsonArr['storeName'];
                                    $shopInfo['shop_keeper']=$matches2[1];
                                    $shop=new Shop();
                                    if($shop->save($shopInfo)){
                                        echo "<script>alert('店铺绑定成功！');location.href='/task/shoplist';</script>";exit;
                                    }else{
                                        echo "<script>alert('店铺绑定失败，请稍候重试或联系客服进行绑定！');location.href='/task/bindtb';</script>";exit;
                                    }
                                }
                            }else{
                                echo "<script>alert('店铺绑定失败，您的店铺未缴纳保证金！');location.href='/task/bindtb';</script>";exit;
                            }
                        }
                    }
                }else{
                    echo "<script>alert('请输入商品链接后再提交！');location.href='/task/bindtb';</script>";exit;
                }
            }
            $string="AB0C2D1E3FG4H5IJKL6MNOP7QR8STU9VWXYZ";
            $randNum="";
            for($i=0;$i<5;$i++){
                $randNum.=$string[rand(0,strlen($string)-1)];
            }
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'randNum'=>$randNum
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //绑定京东店铺
    public function bindjdAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            if($this->request->isPost()){
                $data=$this->request->getPost();
                if(!empty(trim($data['storeLink']))){
                    $shopInfo=array();
                    $shopInfo['shop_user_id']=$this->session->get('userId');
                    $shopInfo['shop_time']=time();
                    $shopInfo['shop_type']=2;
                    $contents=file_get_contents($data['storeLink']);
                    $contents=iconv("GBK", "utf-8",$contents);
                    if(preg_match("/<div.*?class=\"popbox-inner\".*?<a.*?>(.*?)<\/a>/is",$contents,$matches)){
                        $shopInfo['shop_name']=$matches[1];
                        $shopInfo['shop_keeper']=$matches[1];
                        $shop=new Shop();
                        if($shop->save($shopInfo)){
                            echo "<script>alert('店铺绑定成功！');location.href='/task/shoplist';</script>";exit;
                        }else{
                            echo "<script>alert('店铺绑定失败，请稍候重试或联系客服进行绑定！');location.href='/task/bindjd';</script>";exit;
                        }
                    }else{
                        echo "<script>alert('店铺绑定失败，请检查您的商品链接是否正确或联系客服进行绑定！');location.href='/task/bindjd';</script>";exit;
                    }
                }else{
                    echo "<script>alert('请输入商品链接后再提交！');location.href='/task/bindjd';</script>";exit;
                }
            }
            $string="AB0C2D1E3FG4H5IJKL6MNOP7QR8STU9VWXYZ";
            $randNum="";
            for($i=0;$i<5;$i++){
                $randNum.=$string[rand(0,strlen($string)-1)];
            }
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'randNum'=>$randNum
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //绑定其他店铺
    public function bindrestAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin
            ));
        }else{
            $this->response->redirect("/");
        }
    }
    //绑定店铺列表
    public function shoplistAction(){
        $isLogin=$this->isLogin();
        if($isLogin){
            $shopNum=array();
            $userId=$this->session->get('userId');
            $condition="shop_user_id=?1";
            $param=array(1=>$userId);
            //店铺列表
            $shopList=Shop::find(array(
                $condition,
                "bind"=>$param,
                "order"=>"shop_time desc"
            ));
            //计算每个店铺发布任务数
            foreach($shopList as $item){
                $num=0;
                $condition="task_shop_id=".$item->shop_id;
                $taskList=Task::find(array($condition));
                foreach($taskList as $v){
                    $num+=$v->task_num;
                }
                $shopNum[]=$num;
            }
            $this->view->setVars(array(
                'navFirst'=>2,
                'isLogin'=>$isLogin,
                'shopList'=>$shopList,
                'shopNum'=>$shopNum
            ));
        }else{
            $this->response->redirect("/");
        }
    }
}
?>